﻿using AppSocketService;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace AppSocketControl.NOTUSE
{
    public class TCPHandle: SocketHandle
    {
        private IPEndPoint ipLocalPoint;
        private IPEndPoint RemotePoint;
        private TcpListener tcpListener;
        private TcpClient tcpClient;
        private bool RunningFlag = false;
        private const int maxLength = 64512; 
         
        public void Init(string ipAddress, string prot) {
            //得到本机IP，设置UDP端口号     
            IPAddress ip = GetValidIP(ipAddress);
            int port = GetValidPort(prot);
            ipLocalPoint = new IPEndPoint(ip, port);
            tcpListener = new TcpListener(ipLocalPoint);
            tcpListener.Start();
            
            tcpClient = tcpListener.AcceptTcpClient();

            //启动一个新的线程，执行方法this.ReceiveHandle，  
            //以便在一个独立的进程中执行数据接收的操作 

            RunningFlag = true;
            Thread thread = new Thread(new ThreadStart(this.ReceiveHandle));
            thread.Start();
        }

        #region 处理线程
        //定义一个委托  
        public delegate void MyInvoke(string strRecv);
        private void ReceiveHandle()
        {
            NetworkStream stream = tcpClient.GetStream();
            //接收数据处理线程
            while (RunningFlag)
            {
                try
                {
                    byte[] data = new byte[maxLength];
                    int length = stream.Read(data, 0, maxLength);

                    string message = Encoding.UTF8.GetString(data, 0, length);
                    
                    //if (long.TryParse(message, out long userId))
                    //{
                    //    //this.messageHandle.HeartbeatProcess(userId, RemotePoint, tcpClient);
                    //}
                    //else
                    //{
                    //    //this.messageHandle.Process(message, RemotePoint, udpClient);
                    //}
                }
                catch (Exception ex)
                {
                    UpdateMsgTextBox("错误：" + ex.Message);
                }

            }
            stream.Close();
            tcpClient.Close();
            tcpListener.Stop();
        }

        private void UpdateMsgTextBox(string msg)
        {
            //接收数据显示  
            Console.WriteLine(msg);
        }
        #endregion
    }
}
